package com.sakura.controller;

import com.sakura.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
public class StudentController {
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/set")
    public void set(@RequestBody Student student){
        System.out.println(student);
        redisTemplate.opsForValue().set("student",student);
    }

    @GetMapping("/get/{key}")
    public Student get(@PathVariable("key") String key ){
        return (Student) redisTemplate.opsForValue().get(key);
    }

    @DeleteMapping("/delete/{key}")
    public boolean delete(@PathVariable("key") String key){
        redisTemplate.delete(key);
        return redisTemplate.hasKey(key);
    }

    @GetMapping("/string")
    public String stringTest(){
        redisTemplate.opsForValue().set("str","Hello World!");
        String str = (String) redisTemplate.opsForValue().get("str");
        return str;
    }

    @GetMapping("/list")
    public List<String> listTest(){
        ListOperations<String, String> listOperations = redisTemplate.opsForList();
        //从左边添加
        listOperations.leftPush("list","left");
        listOperations.leftPush("list","left1");
        //从右边添加
        listOperations.rightPush("list", "right");
        listOperations.rightPush("list", "right1");

        //利用下标来取数据，这里取left和left1
        List<String> list = listOperations.range("list", 0, 1);
        return list;
    }

    @GetMapping("/set")
    public Set<String> setTest(){
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        setOperations.add("set", "Hello");
        setOperations.add("set", "Hello");
        setOperations.add("set", "World!");
        setOperations.add("set", "World!");
        Set<String> set = setOperations.members("set");
        return set;
    }

    @GetMapping("/zset")
    public Set<String> zsetTest(){
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.add("zset", "Hello", 1);
        zSetOperations.add("zset", "World", 2);
        zSetOperations.add("zset", "Java", 3);

        Set<String> zset = zSetOperations.range("zset", 0, 2);
        return zset;
    }

    @GetMapping("/hash")
    public void hashTest(){
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        hashOperations.put("key","hashKey","Hello");
        String s = hashOperations.get("key", "hashKey");
        System.out.println(s);
    }
}
